<?php

class Comments
{
    private $pageID;

    public function __construct($pageID)
    {
        $this->pageID = $pageID;
    }

    public function Update()
    {
        $comment = Request::GetParam('comment');
        if ( !empty($comment) )
        {
            $ip = $_SERVER['REMOTE_ADDR'];
            Core::DBConn()->Query(
                "
                INSERT INTO comment 
                  SET 
                    text = #comment#,
                    date = NOW(),
                    ip = #ip#,
                    id_page = #pageId#
                ",
                Util::QuoteArray( array(
                    '#comment#' => $comment,
                    '#ip#'      => $ip,
                    '#pageId#'  => $this->pageID
                ) )
            );
        }
    }

    public function Generate()
    {
        $ip = $_SERVER['REMOTE_ADDR'];
        $res = Core::DBConn()->Query(
            "
            SELECT text 
            FROM comment 
            WHERE id_page = #pageId# AND (active=1 OR ip=#ip#)
            ORDER BY date DESC
            ",
            Util::QuoteArray( array(
                '#ip#'      => $ip,
                '#pageId#'  => $this->pageID
            ) )
        );

        $comments = $res->GetAllAssoc();
        $tmpl = Core::CreateTemplateEngine( PATH_TEMPLATES ."include/comments/" );
        $tmpl->define("comment_form",   'comment_form.tpl');
        $tmpl->define("comment",        'comment_td.tpl');

        $tmpl->set('COMMENTS_COUNT', count($comments));
        foreach ( $comments as $comment )
        {
            $comment = $comment['text'];
            $comment = nl2br( Util::GetHtmlEntities($comment) );
            $tmpl->set('TEXT', $comment);
            $tmpl->parse("COMMENTS", '.comment');
        }

        $tmpl->parse("COMMENTS", "comment_form");
        return $tmpl->getGenerated();
    }
}

?>